package utils;

import org.apache.log4j.Logger;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Servlet implementation class for Servlet: ImageGenerator
 * 
 */
public class NumImgGenServlet extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(NumImgGenServlet.class);

    /**
     * 
     */
    private static final long serialVersionUID = 4697629612100223036L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        OutputStream out = response.getOutputStream();
        response.setContentType("image/jpeg"); // 必须设置ContentType为image/jpeg
        String[] randVals = new String[4];// 设置默认生成4个数字
        Date d = new Date();
        long lseed = d.getTime();
        Random r = new Random(lseed); // 设置随机种子
        StringBuilder digitCode = new StringBuilder();
        for (int i = 0; i < randVals.length; i++) {
            randVals[i] = String.valueOf(r.nextInt(9));
            digitCode.append(randVals[i]);
        }
        // 放入sessoin
        request.getSession().setAttribute("digitCode", digitCode.toString());
        // 创建内存图像

        BufferedImage bi = ImageIO.read(new File(this.getServletContext()
                .getRealPath("images/numpic.JPG")));
        // 可以在上面读入一个背景图，然后在背景图上写数字

        Graphics2D g = bi.createGraphics();
        g.setColor(Color.BLUE);
        int fontSize = 16;
        g.setFont(new Font(null, Font.BOLD, fontSize));
        for (int i = 0; i < randVals.length; i++) {
            g.drawString(randVals[i], bi.getWidth() / 4 + i * 14, bi
                    .getHeight() / 2+5);
        }

        try {
            // 使用JPEG编码，输出到response的输出流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
            param.setQuality(1.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(bi);
        } catch (Exception ex) {
            out.write(ex.toString().getBytes());
            logger.error("gen picture err ", ex);
        }
    }
}
